#!/usr/bin/python3
# -*- coding: UTF-8 -*-

from app import App
from utils.tools import Tools
from time import time
import datetime
# from os import popen as osPopen, path as osPath  # 管道处理
import sys as osSys
import math
import gol
import xml.etree.ElementTree as ET
import logging


gol._init()


class Application(App):
    # 初始配置
    def __init__(self):
        super().__init__()
        logger = logging.getLogger("uiautomator2")
        logger.setLevel(logging.DEBUG)
        # 执行动作 [0 - 走路赚元宝: walk, 1 - 打工赚元宝: work, 2 - 摇一摇赚元宝: shake]
        self.iActionType = 2
        self.tupActionMap = {
            0: '走路赚元宝',
            1: '打工赚元宝',
            2: '摇一摇赚元宝'
        }
        self.oMapList = [
            { # 赚步数
                'name': '走路赚元宝', 'type': 't',
                'icon': 'O1CN01IeRzpJ1hSSJ53VxuH_!!6000000004276-2-tps-116-132.png_',
                'headerImg': 'O1CN010NIcmW264yPEFQS2o_!!6000000007609-2-tps-750-214.png_'
            },
            { # 赚体力
                'name': '打工赚元宝', 'type': 't',
                'icon': 'O1CN01vWC7gg20DmKvWaURW_!!6000000006816-2-tps-248-246.png_',
                'headerImg': 'O1CN01ExSUrC1ovx8kzkMgT_!!6000000005288-2-tps-750-214.png_'
            },
            { # 赚次数
                'name': '摇一摇赚元宝', 'type': 'p',
                'icon': '//*[@resource-id="page"]/android.view.View[2]/android.view.View[2]/android.view.View[1]/android.view.View[2]/android.view.View[1]',
                'headerImg': 'O1CN01il23fK1s4bT7kT7fL_!!6000000005713-2-tps-750-214.png_'
            },
        ]
        self.iDisplayHeight = self._d.info.get('displayHeight') - 5
        self.iDisplayRight = self._d.info.get('displayWidth') - 100
        self.iDHB300 = self.iDisplayHeight - 300 # 底高300
        self.iHMove = 216 # 滚动高度bounds
        self.iCountDown = 0 # 倒计时
        self.watcher = None
        self.appId = 'com.taobao.live/.home.activity.TaoLiveHomeActivity'


    # ////////////---------------
    # nav 路径
    # 启动
    def startApp(self, isClose=False):
        if (isClose):
            self._d.app_stop(self.appId)
            self._d.app_clear(self.appId)
            self.tool.setSleep(4)
        self.tool.callApp(self.appId)
        self.tool.setSleep(4)
        return self

    # 关闭打工赚钱 - 弹窗
    def closeWYYDHZQ(self):
        self.tool.setSleep(2)
        bNode, oNode = self.el2('t', 'O1CN01WOnRmx1JJhubZYFtu_!!6000000001008-2-tps-560-656.png_')
        if bNode:
            self._d.xpath('//*[@resource-id="delivery-modal"]/android.view.View[2]/android.view.View[1]').click()
            self.tool.setSleep(1)
        # 新活动窗窗
        self._d(resourceId='com.taobao.live:id/tl_dx_card_container').child(className='android.widget.FrameLayout').child(className="android.widget.ImageView", index=3).click_exists(timeout=2)


    # 进入到元宝中心
    def startYuanBaoZhongxin(self):
        # 首页 - 我的
        def tapWD():
            self.tool.setSleep(2)
            bNode = self._d.xpath('//*[@resource-id="com.taobao.live:id/hp3_bottom_tab"]/android.widget.LinearLayout[1]/android.support.v7.app.ActionBar-Tab[4]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.ImageView[1]').click_exists(timeout=2)
            self.myEcho("我的", bNode)
            self.tool.setSleep(4)

        # 元宝中心
        def tapYuBaoZhongXin():
            self.tapNode("t", "元宝中心")
            # 关闭弹窗
            self.closeWYYDHZQ()
            self.tool.setSleep(4)
        
        tapWD()
        tapYuBaoZhongXin()
        return self

    def start(self, up=True):
        self.startApp().startYuanBaoZhongxin()
        return self



    # 跳下一个节点动作
    def tapYB3Activity(self, sType, iIndex, isClick = False):
        iTmpIndex = int(iIndex)
        oMapList = self.oMapList
        # print(
        #     '%s <-> %s <-> %s'
        #     %(self.tupActionMap[iTmpIndex], oMapList[iTmpIndex]['name'], '菜单' if sType == 'text' else '按钮')
        # )
        if (sType == 'text'):
            return self.el2CE("t", oMapList[iTmpIndex]['name']) if isClick else self.el2("t", oMapList[iTmpIndex]['name'])
        else:
            sTmpType = oMapList[iTmpIndex]['type']
            # 校验是否已经点开半屏弹窗 - 防误点
            oHeaderImg = self.el2("t", oMapList[iTmpIndex]['headerImg'])
            if (isClick and not oHeaderImg[0]):
                oIconImg = self.el2(sTmpType, oMapList[iTmpIndex]['icon'])
                bNode = oIconImg[1].click_exists(timeout=1)
                return bNode
            return True

    # 走路赚元宝
    def baseWalk(self):
        self.iActionType = 0
        # 路径：元宝中心 - 走路赚元宝
        self.tapYB3Activity('text', self.iActionType, True)
        self.tool.setSleep(2)
        return self

    def baseWork(self):
        self.iActionType = 1
        # 路径：元宝中心 - 打工赚元宝
        self.tapYB3Activity('text', self.iActionType, True)
        self.tool.setSleep(2)

    def baseShake(self):
        self.iActionType = 2
        # 路径：元宝中心 - 打工赚元宝
        self.tapYB3Activity('text', self.iActionType, True)
        self.tool.setSleep(2)
    # ////////////---------------


    # ///三大任务/////////---------------
    def getWalk(self):
        self.baseWalk()
        # 左边 “领取” 按钮
        # 校验是否已经点开半屏弹窗 - 防误点
        oHeaderImg = self.el2("t", self.oMapList[0]['headerImg'])
        if (not oHeaderImg[0]):
            self.tapNode("t", "领取")
            self.tool.setSleep(3)
        # 右边 “赚步数” 按钮
        self.tapYB3Activity('icon', self.iActionType, True)
        self.tool.setSleep(2)

    # 打工赚元宝
    def getWork(self):
        self.baseWork()
        # 校验是否已经点开半屏弹窗 - 防误点
        oHeaderImg = self.el2("t", self.oMapList[2]['headerImg'])
        if (not oHeaderImg[0]):
            # 左边领体力 “去领取” 按钮
            self.tapNode('t', '去领取')
            self.tool.setSleep(3)
        # 右边 “赚体力” 按钮
        self.tapYB3Activity('icon', self.iActionType, True)
        self.tool.setSleep(2)

    # 摇一摇
    def getShake(self):
        self.baseShake()
        # 右边 “赚次数” 按钮
        self.tapYB3Activity('icon', self.iActionType, True)
        self.tool.setSleep(2)
    # ////////////---------------




    # 打工赚元宝 -> 去打工赚钱
    def tapQDGZQ(self):
        print(">>> 去打工赚钱")
        self.tapNode("id", "action-main")
        self.tool.setSleep(2)
        bNode, = self.tapNode("t", "+888")
        if (bNode):
            self.tapNode("t", "开始打工")


    # 复用动作
    def reuseActions(self, anyFindTxt, sFindTxtSec, iTime, iType, bBack=True):
        iStartTime = time()
        # 匹配list节点（直播，视频）
        if (not sFindTxtSec):
            oClickNode = self._d(textMatches=anyFindTxt)
        else:
            oClickNode = self._d(textMatches=anyFindTxt).sibling(text=sFindTxtSec)
        # print('oClickNode', oClickNode)
        if (not oClickNode):
            return False
        
        bCanClick = oClickNode.exists(timeout=1)
        # print('bCanClick', oClickNode, bCanClick)

        if (bCanClick):
            try:
                tupCenter = oClickNode.info.get('bounds')
                # 是否超过屏高
                assert tupCenter or int(tupCenter['bottom']) > int(self.iDisplayHeight)
                hasClick = oClickNode.click_exists(timeout=2)
                # print('hasClick', hasClick)
                assert hasClick
                hasBack = False
                print('成功', end="")
                if (iType == 2): # 视频类的上划
                    self.goRun(iTime)
                    hasBack = True
                elif (iType == 3): # 小视频
                    # self.iStepTime = iTime
                    gol.set('iStepTime', iTime)
                    if (self._d(text='逛街得奖励').exists(timeout=3)):
                        self.goRun(iTime + 10)
                        hasBack = True
                    elif (
                        (self._d(resourceId='com.taobao.live:id/back').exists and self._d(resourceId='com.taobao.live:id/tl_task_reminder_image').exists) or
                        (self._d(resourceId='com.taobao.live:id/taolive_close_btn').exists and (self._d(text='关注').exists or self._d(resourceId='com.taobao.live:id/taolive_unfavorite').exists)) or
                        (self._d(resourceId='com.taobao.live:id/back').exists and self._d(text='关注').exists) or
                        (self._d(text='wgMnATk1bsIA0md6FB0AD8KHBf7KFFMCbmP+TPwMtB64VfoE6NFGigsnPcelgIbfb3iutILLOVmUZkGgk4+UC4NtghY9Q0wN5RvA2kQ440j5BUC9TKQThnWhU7G3FrITzDKBH6Tw8X9Wi0s3Rg6ZatkIF391DTuvT6gIKdKGpEepIp49LwnelCCbHxOTfxnrIKp9ySgLR3+B5Q1WQTJDONDAAAAAElFTkSuQmCC').exists)
                    ):
                        self.countDown()
                        hasBack = True
                    else:
                        # self.shortVideoWatch()
                        self.countDown()
                else: # 直播类直接等时间
                    gol.set('iStepTime', iTime)
                    self.countDown()

                print(" 用时：%d" % (int(time() - iStartTime)))
                self.tool.setSleep(1)
                if ((bBack and not iType == 3) or hasBack == True):
                    # print('back')
                    self._d.press("back")
                    self.tool.setSleep(1)
                return True
            except Exception as e:
                print(f"Unexpected error: {e}")
                return False
        return False


    # 重复动作
    def goRun(self, iTime, sType='upl'):
        sleepStep = 6
        i = math.ceil(iTime / sleepStep) + 3 # 多加上划补充卡顿问题造成的事故
        tmpType = sType
        while i > 0:
            print("\r", end="")
            print("进度: {}: ".format(i), "▓" * (i), end="", flush = True)
            osSys.stdout.flush()
            self.tool.setSleep(sleepStep)
            pos = self.tool.moveDirection(tmpType)
            self.tool.move(pos)
            i -= 1

    # 列表迭代器 - 处理tupList的重复赋值过程
    def listIterator(self, tupList):
        iStart = int(self.iNextIndex) if self.iNextIndex else 0
        for iIndex, tupItem in enumerate(tupList[int(iStart):]):
            tupItem = list(tupItem)
            print(self.tupActionMap[self.iActionType],  ' - ', iIndex, ' - ', tupItem)
            if (tupItem[0] == '看黄金档直播并下单'):
                iCount = 0
                if (self._d(text='看黄金档直播并下单').sibling(index=5).exists):
                    iCount = self._d(text='看黄金档直播并下单').sibling(index=5).get_text()
                iStep = int(tupItem[3]) - int(iCount)
            else:
                iStep = tupItem[3]
            while iStep > 0:
                self.tool.setSleep(1)
                self.tapYB3Activity('icon', self.iActionType, True)
                self.tool.setSleep(1)
                bToDo = self.reuseActions(tupItem[0], tupItem[1], tupItem[2], tupItem[4])
                # print('bToDo', bToDo)
                if (not bToDo):
                    iStep = 0
                    break
                self.tool.setSleep(4)
                iStep -= 1

    # 迭代器 跑完视频项目
    def routines(self):
        # 查询关键词，次关键词，循环执行次数, 类型{1:直播， 2:视频}
        tupListBefore = (
            ("看直播60秒", "去完成", 65, 10, 1),
            ("看直播60秒", "去观看", 65, 10, 1),
            ("看直播90秒", "去完成", 95, 10, 1),
            ("看视频90秒", "去完成", 130, 10, 1),
            ("看视频60秒", "去完成", 80, 10, 2),
            ("看视频60秒", "去观看", 80, 10, 2),
            ("看好物视频60秒", "去完成", 80, 10, 2),
            ("浏览好货卖场30秒", "去完成", 80, 5, 2),
            ("浏览精选推荐60秒", "去完成", 80, 10, 2),
            ("看精彩内容60秒", "去完成", 90, 10, 2),
            ("看精彩内容3分钟", "去完成", 240, 5, 2),
            ("看发现好物3分钟", "去完成", 240, 5, 2),
            ("看发现好物2分钟", "去完成", 200, 1, 2),
            ("看视频2分钟", "去观看", 200, 1, 2),
            ("看视频2分钟", "去完成", 200, 1, 2),
            ("看直播2分钟", "去完成", 130, 15, 1),
            ("看直播3分钟", "去完成", 190, 5, 2),
        )
        tupListAfter = (
            ("看晚间视频60秒", "去完成", 80, 3, 2),
            ("看晚间惊喜视频60秒", "去完成", 80, 10, 2),
            ("看黄金8点档直播60秒", "去完成", 65, 10, 1),
            ("看黄金8点档直播60秒", "去观看", 65, 10, 1),
            ("看黄金直播60秒", "去观看", 65, 10, 1),
            ("看晚间精彩内容60秒", "去完成", 90, 10, 2),
            ("看晚间惊喜视频90秒", "去完成", 130, 10, 2),
            ("看黄金8点档直播90秒", "去完成", 95, 10, 1),
            ("看黄金8点档直播90秒", "去观看", 95, 10, 1),
            # ("看视频90秒", "去完成", 130, 5, 2),
            # ("看直播90秒", "去完成", 95, 10, 1),
            ("看黄金档直播并下单", "去完成", 130, 15, 1),
            ("看黄金直播2分钟", "去完成", 130, 10, 1),
            ("看黄金8点档直播2分钟", "去完成", 130, 15, 1),
            ("看直播2分钟", "去完成", 130, 15, 1),
            ("看黄金8点档直播3分钟", "去完成", 190, 10, 1),
            ("看专享直降直播3分钟", "去完成", 190, 1, 2),
            ("看优价好物直播3分钟", "去完成", 190, 1, 2),
            ("看视频3分钟", "去完成", 240, 5, 2),
            ("看直播3分钟", "去完成", 190, 5, 2),
        )
        
        now = datetime.datetime.now()
        tupList = tupListBefore + tupListAfter
        if self.sAction == 'aa' or ('a' in self.sAction[2:]):
            if now.hour < 18:
                tupList = tupListBefore
            else:
                tupList = tupListAfter

        # 调起半屏弹窗
        self.tapYB3Activity('icon', self.iActionType, True)
        self.tool.setSleep(1)
        self.listIterator(tupList)


    # 下划一下列表，滚动到列表头部
    def toMoveToUp(self):
        for i in range(2):
            self.tool.move([600, self.iDHB300 - self.iHMove * 3, 600, self.iDHB300])
            self.tool.setSleep(1)

    def toBrowse(self, num):
        # 查询关键词，等待时间
        tupList = (
            ("浏览省钱专区30秒", "去完成", 46),
            ("浏览当季上新好物30秒", "去完成", 46),
            ("浏览省钱专区60秒", "去完成", 80),
            ("浏览当季上新好物60秒", "去完成", 80),
            ("浏览上新日历30秒", "去完成", 46),
            ("浏览精选推荐20秒", "去浏览", 36),
            ("浏览精选推荐30秒", "去完成", 46),
            ("浏览元宝商城30秒", "去浏览", 46),
            ("浏览天天特卖20秒", "去完成", 36),
            ("浏览店铺", "去完成", 46),
            ("浏览直播大侦探30s", "去完成", 46),
            ("浏览精选推荐30秒", "去浏览", 46),
            ("浏览精选推荐30秒", "去完成", 46),
            ("浏览好货卖场30秒", "去完成", 46),
            ("浏览上新日历", "去浏览", 46),
            ("浏览精选推荐60秒", "去完成", 80),
            ("看好看直播间60秒", "去完成", 80),
        )
        # 调起半屏弹窗
        self.tapYB3Activity('icon', self.iActionType, True)
        if (num == 1):
            self.tool.move([600, self.iDHB300, 600, self.iDHB300 - self.iHMove * 2])
            self.tool.setSleep(1)

        for iIndex, tupItem in enumerate(tupList):
            tupItem = list(tupItem)
            print(tupItem)
            self.reuseActions(tupItem[0], tupItem[1], tupItem[2], 2)   
            # 搜索商品或主播
            # self.getSearchProductAndAnchor()
        print('-' * 5)
        if (num >= 1):
            # self.el2CE('t', self.oMapList[self.iActionType]['headerImg'])
            self.toMoveToUp()


    # 循环领取走路金币
    def goWalkGold(self):
        # 领取走路元宝
        def getWalkGold():
            bNode = self.tapNode('tc', '8元宝')
            if (bNode[0]):
                self.tool.setSleep(2)
                self.reuseActions('额外领至少58元宝', '', 80, 3)
        i = 10
        while i > 0:
            getWalkGold()
            i -= 1


    # 走路赚完宝 打工赚元宝 - 上滑赚体力
    def justUp(self):
        self.goRun(400)

    # 点淘鸭家园 - 种田动作        
    def farm(self):
        def farmReDo():
            oCLEs = self._d(text='+6')
            tupPos = set({})
            # 不缓存会数据有问题
            for oView in oCLEs:
                oPos = oView.info['bounds']
                tupPos.add((oPos['left'], oPos['top']))
            for pos in tupPos:
                self._d.click(pos[0], pos[1])
                self.tool.setSleep(3)
                self.el2CE('t', '卷心菜')
                self.tool.setSleep(3)
            self.tool.setSleep(40 - len(tupPos) * 2)
        
        if (self.bStart):
            self._d.swipe_ext("left", scale=0.8)
            self._d.swipe_ext("left", scale=0.8)
            # 是否已经调起弹窗
            bPopup, oPopupNode = self.el2('t', 'O1CN01TlFJY51WfmA0MdCbw_!!6000000002816-2-tps-311-73.png_Q75.jpg_')
            if (not bPopup):
                oClickFarm = self.el2('t', '种子商店')
                if (oClickFarm[0]):
                    oClickFarm[1].click_exists(timeout=1)
                    self.tool.setSleep(2)
            # 下划点
            drowTop = oPopupNode.info['bounds']['bottom'] + 50
            # 下划一下到第一排
            self.tool.move([600, drowTop, 600, self.iDisplayHeight - 50])
            self.tool.setSleep(1)
            self.tool.move([600, drowTop, 600, self.iDisplayHeight - 50])
            self.tool.setSleep(1)
            self.tool.move([600, drowTop, 600, self.iDisplayHeight - 50])
            self.tool.setSleep(1)
        i = 60
        while i > 0:
            farmReDo()
            i -= 1


    # 点淘鸭家园 - 任务得金币
    def task(self):
        if (not self._d(text='O1CN01TTR5B828XUMclWSBH_!!6000000007942-2-tps-746-400.png_Q75.jpg_').exists):
            self.el2CE('t', '点淘鸭家园')
            self.tool.setSleep(2)
            self.el2CE('t','O1CN014gUZhI1qRqOqWyG2s_!!6000000005493-2-tps-276-278.png_220x10000Q75.jpg_')
            self.tool.setSleep(1)
        tupList = (
            # ("体验AI免费拍情侣大片", "去完成", 46, 1, 2),
            ("看直播60秒", "去完成", 70, 10, 1),
            ("看视频60秒", "去完成", 80, 10, 2),
            ("浏览精选推荐30秒", "去完成", 40, 1, 2),
            ("看好物视频60秒", "去完成", 80, 10, 2),
            ("看好看直播间60秒", "去完成", 80, 10, 2),
            ("浏览主播专属福利15s", "去完成", 20, 1, 2),
            ("浏览618低价秒杀15s", "去完成", 20, 1, 2),
            ("前往游戏中心", "去完成", 40, 1, 2),
            ("浏览精选推荐60秒", "去完成", 80, 1, 2),
            ("浏览直播大侦探30s", "去完成", 46, 1, 2),
            ("浏览省钱专区60秒", "去完成", 80, 1, 2),
            ("浏览当季上新好物60秒", "去完成", 80, 1, 2),
            ("看黄金档直播2分钟", "去完成", 80, 10, 3),
            ("看小视频", "去完成", 80, 10, 3),
            ("看小视频", "去完成", 80, 10, 3),
            ("看小视频", "领福利", 80, 5, 3),
            ("看小视频", "领福利", 80, 10, 3),
        )
        self.listIterator(tupList)
        if (self.watcher):
            try:
                self.watcher.stop()
                self.watcher = None
            except:
                print('self.watcher.stop()')

    # 列表 - 签到60秒
    def signIn(self):
        self._d(scrollable=True).scroll(steps=40)
        if (self.el2CE('t', '今日签到')):
            # 等待一下弹窗
            self.tool.setSleep(4)
            oCheckNode = self.el2('t', '看直播60秒再得68元宝')
            if (not oCheckNode[0]):
                # 如果没有弹窗, 尝试点击‘开’字
                if (self.el2CE('t', 'O1CN01AqnTGR1k2IUAgzn0I_!!6000000004625-2-tps-254-263.png_')):
                    if (self.el2CE('t', '看直播60秒再得68元宝')):
                        self.tool.move([600, self.iDHB300 - self.iHMove * 2, 600, self.iDHB300])
                        self.tool.setSleep(70)
                        self._d.press("back")
                        return
            self._d.press("back")


    # 右上角 - 领取奖励
    def topRightRewad(self):
        print('右上角 - 领取奖励')
        iStep = 3
        while iStep >= 0:
            if (self.el2CE('t', '领取奖励')):
                print('右角元宝:', iStep)
                if (self._d(text='邀请好友 再赚46元').exists(timeout=2)):
                    # 关闭弹窗
                    self.el2CE('t', 'O1CN01LxFPWH1Mmy2hurJW4_!!6000000001478-2-tps-54-54.png_')
                    return
                if (self.el2CE('t', '看直播60秒得68元宝')):
                    self.tool.countDown(70)
                    self._d.press("back")
            iStep -= 1
        self.tool.setSleep(1)


    # 打工赚元宝 - 右上角50体力
    def get50tl(self):
        print('打工赚元宝 - 右上角50体力')
        self.iActionType = 1
        self.tapYB3Activity('text', self.iActionType, True)
        if (self.el2CE('tc', '30秒送50体力')):
            self.tool.countDown(46, 'up')
            self._d.press("back")

    # -----------------------
    # 下单返购物金
    def getCashback(self):
        def getCashbackLoop(iIndex = 0):
            # 取两个循环对象
            oNode = self._d(text='看直播60秒得购物金')
            if (oNode.exists(timeout=2) and oNode.count >= 1):
                if (iIndex >= oNode.count):
                    return
                oNode = oNode[iIndex]
                iMax = oNode.sibling(index=6).get_text()[1:]
                iCurrent = oNode.sibling(index=5).get_text()
                iCurrent = int(iCurrent) if iCurrent.isnumeric() else 0
                while iCurrent < int(iMax):
                    self.reuseActions('看直播60秒得购物金', '', 65, 1)
                    iCurrent += 1
                    self.tool.setSleep(1)

        if (self._d(text='下单返购物金').exists(timeout=1)):
            self.el2CE('t', '下单返购物金')
            self.tool.setSleep(1)
            
        if (not self._d(text='去下单').exists(timeout=1)):
            self.tool.setSleep(1)
            self.el2CE('t', '去下单')
        if (not self._d(text='去下单').exists(timeout=1)):
            self.tool.setSleep(1)
            self.el2CE('t', '去下单')
            
        if (not self._d(text='O1CN01xzpsJ91IH8Ds8QZLd_!!6000000000867-2-tps-1500-596.png_').exists(timeout=2)):
            self.el2CE('t', '做任务赚购物金')

            self.tool.setSleep(1)
            getCashbackLoop(0)
            getCashbackLoop(1)
            self.tool.move([600, self.iDHB300, 600, self.iDHB300 - self.iHMove * 5])
            self.tool.setSleep(1)
            self.tool.move([600, self.iDHB300, 600, self.iDHB300 - self.iHMove * 5])
            self.tool.setSleep(1)
            self.tool.move([600, self.iDHB300, 600, self.iDHB300 - self.iHMove * 5])
            for i in range(10):
                self.reuseActions('看直播60秒', '去完成', 65, 1)
            self.el2CE('t', 'O1CN01qE4nNy1M45HMjL7jz_!!6000000001380-2-tps-60-60.png_')
            self.el2CE('t', '签到')
        self._d.press("back")
    # -----------------------

    # 搜索商品或主播
    def getSearchProductAndAnchor(self):
        if (self._d(text='搜索商品或主播').sibling(text='去完成').click_exists(timeout=2)):
            self.tool.setSleep(2)
            oNode = self._d(resourceId='com.taobao.live:id/taolive_search_history_words').child(className='android.widget.TextView')
            if (oNode[0].exists):
                oNode[0].click_exists(timeout=2)
                self.tool.setSleep(3)
                self._d.press("back")
            self._d.press("back")

    # 逛逛商城的真香秒杀
    def getFlashKilling(self):
        if (self._d(text='逛逛商城的真香秒杀').sibling(text='去完成').click_exists(timeout=2)):
            self.tool.setSleep(2)
            if (self._d(text='“真香秒杀”').exists):
                self.el2CE('t', '抢')
                self.tool.setSleep(2)
                self._d.press("back")
            self._d.press("back")


    # 小视频类
    def shortVideo(self):
        tupList = (
            ("看精彩小视频", "去完成", 80, 20, 3),
            ("看小视频", "去完成", 80, 10, 3),
            ("看小视频", "领福利", 80, 10, 3),
            ("看小视频领奖", "去完成", 80, 10, 3),
            ("看惊喜小视频", "去完成", 80, 10, 3),
            ("看精选小视频", "去完成", 80, 10, 3),
        )
        self.listIterator(tupList)
        if (self.watcher):
            try:
                self.watcher.stop()
                self.watcher = None
            except:
                print('self.watcher.stop()')

    # 小视频监听回调
    def shortVideoWatch(self):
        def goShortVideoCall():
            self.tool.setSleep(4)
            # self.iStepTime = 0
            gol.set('iStepTime', 0)
            if (not self._d(textMatches='跳过').click_exists(timeout=2)):
                self._d(resourceId='com.byted.pangle:id/tt_reward_full_count_down_after_close').click_exists(timeout=2)

        if (not self.watcher):
            self.watcher = self._d.watch_context()
            self.watcher.when('//*[@textStartsWith="恭喜完成任务,获得"]').call(goShortVideoCall())
            # self.watcher.when('//*[@text="坚持退出"]').click()
            self.watcher.start()


    # 睡觉收益
    def goSleep(self):
        def toSleep():
            tupList = (
                ("看好货卖场", "", 80, 1, 2),
                ("看精选推荐", "", 80, 1, 2),
                ("看省钱专区", "", 80, 1, 2),
                ("看上新好物", "", 80, 1, 2),
                ("看小视频", "", 80, 1, 1),
                ("看直播60秒", "", 65, 1, 1),
            )
            self.listIterator(tupList)

        if (self.bStart):
            self.start()
            self._d(scrollable=True).scroll(steps=40)
            self.tool.setSleep(1)
            self.el2CE('t', '睡觉赚元宝')
            self.tool.setSleep(2)
        toSleep()


    def cardCollecting(self):
        tupList = (
            ("看直播60秒", "", 80, 10, 1),
            ("看好物视频60秒", "", 80, 10, 2),
            ("看直播60秒", "", 80, 10, 1),
            ("看精彩小视频", "", 80, 10, 3),
            ("看小视频", "", 80, 1, 1),
        )
        self.listIterator(tupList)



class WatcherPopup(App):
    # 初始配置
    def __init__(self):
        super().__init__()
        self.watcher = None
        self.clickPrev = None

    def callBack(self, d, el):
        # print("self.clickPrev -1", self.clickPrev)
        # 延时的时间 - 秒
        if (self.clickPrev == None):
            self.clickPrev = int(time())
            # print("self.clickPrev -2", self.clickPrev)
            el.click()
            gol.set('iStepTime', 0)
            self.tool.setSleep(1)
            self.clickPrev = None
            # print("self.clickPrev -3", self.clickPrev)



    def watchStart(self, aList=[]):
        closeBtn0 = '//android.widget.RelativeLayout/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[4]/android.widget.FrameLayout[1]/android.widget.ImageView[1]'
        closeBtn1 = '//android.widget.RelativeLayout/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.ImageView[1]'
        closeBtn2 = '//android.widget.RelativeLayout/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.ImageView[1]'
        closeBtn3 = '//android.widget.RelativeLayout/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[2]/android.widget.FrameLayout[1]/android.widget.TextView[1]'
        closeBtn4 = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[2]/android.widget.ImageView[1]'
        closeBtn5 = '//android.widget.RelativeLayout/android.widget.FrameLayout[1]/android.widget.FrameLayout[2]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.widget.ImageView[1]'
        closeBtn6 = '//android.widget.RelativeLayout/android.widget.FrameLayout[1]/android.widget.FrameLayout[2]/android.widget.FrameLayout[2]/android.widget.FrameLayout[2]/android.widget.ImageView[1]'
        closeBtn7 = '//android.widget.RelativeLayout/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[2]/android.widget.FrameLayout[1]/android.widget.ImageView[1]'
        closeBtn8 = '//android.widget.RelativeLayout/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[2]/android.widget.FrameLayout[2]/android.widget.ImageView[1]'
        closeBtn9 = '//android.widget.RelativeLayout/android.widget.FrameLayout[1]/android.widget.FrameLayout[2]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]'
        closeBtn10= '//android.widget.RelativeLayout/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.widget.ImageView[1]'
        closeBtn11= '//android.widget.RelativeLayout/android.widget.FrameLayout[1]/android.widget.FrameLayout[2]/android.widget.FrameLayout[2]/android.widget.FrameLayout[1]/android.widget.ImageView[1]'
        closeBtn12= '//android.widget.RelativeLayout/android.widget.FrameLayout[1]/android.widget.FrameLayout[2]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.ImageView[1]'
        closeBtn13= '//android.widget.RelativeLayout/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.ImageView[1]'
        closeBtn14= '//android.widget.RelativeLayout/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[2]/android.widget.ImageView[1]'
        closeBtn15= '//*[@resource-id="android:id/content"]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[2]/android.widget.ImageView[1]'
        closeBtn16= '//android.widget.RelativeLayout/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[4]/android.widget.FrameLayout[3]/android.widget.FrameLayout[2]/android.widget.TextView[1]'


        mreTxt0 = '@text="摇动或点击了解更多内容" or @text="扭动或点击了解更多内容" or @text="扭动试试 了解更多" or @text="扭动/点击下载第三方应用或跳转详情页"'
        mreTxt1 = '@text="查看详情" and @text="4.8"'
        mreTxt2 = '@text="查看详情" or @text="立即抢购" or @text="立即体验" or @text="立即领取" or @text="立即购买" or @text="去微信看看" or @text="观看直播" or @text="了解更多" or @text="立即安装" or @text="立即打开" or @text="下载应用" or @text="立即下载"'

        ctx = self._d.watch_context()
        ctx.when('//*[@text="我知道了"]').click()
        ctx.when('//*[@text="查看更多任务"]').click()
        ctx.when('//*[@text="残忍离开"]').click()
        ctx.when('//*[@text="开心收下"]').click()
        ctx.when('//*[@text="TB1TJ.yhhvbeK8jSZPfXXariXXa-80-80.png_"]').click()
        ctx.when('//*[@resource-id="com.taobao.taobao.liveroom_android_plugin_AType:id/taolive_room_top_close_btn"]').click()
        ctx.when('//*[@text="O1CN01qE4nNy1M45HMjL7jz_!!6000000001380-2-tps-60-60.png_Q75.jpg_"]').click()
        ctx.when('//*[@resource-id="com.byted.pangle:id/tt_reward_full_count_down_after_close"]').click()
        ctx.when('//*[@resource-id="com.byted.pangle.m:id/tt_reward_full_count_down_after_close"]').click()
        ctx.when('//*[@text="恭喜获得奖励" or @text="恭喜获得奖励！"]').when('//android.widget.RelativeLayout/android.widget.LinearLayout[1]/android.widget.ImageView[2]').click()
        ctx.when('//*[@text="close"]').when('//android.widget.ImageView[@index=1]').click()
        # ctx.when('//*[@text="恭喜获得奖励"]').when("//*[%s]"%(mreTxt2)).when(closeBtn12).click()
        # ctx.when('//*[@text="恭喜获得奖励"]').when("//*[%s]"%(mreTxt2)).when(closeBtn13).click()
        ctx.when('//*[@text="超火爆下载中"]').when(closeBtn4).click()
        ctx.when('//*[@text="放弃福利" or @text="放弃奖励离开"]').click()
        ctx.when('//*[@text="抢鲜进入会场"]').when(closeBtn14).click()
        ctx.when('//*[@text="立即查看" or @text="去看看" or @text="查看详情"]').when(closeBtn15).call(self.callBack)
        ctx.when('//*[@text="淘宝" or @text="百度极速版"]').when(closeBtn15).call(self.callBack)
        ctx.when('//*[%s]'%(mreTxt2)).when(closeBtn7).call(self.callBack)
        ctx.when('//*[%s]'%(mreTxt0)).when('//*[%s]'%(mreTxt2)).when(closeBtn10).call(self.callBack)
        ctx.when('//*[%s]'%(mreTxt0)).when('//*[%s]'%(mreTxt2)).when(closeBtn0).call(self.callBack)
        ctx.when('//*[%s]'%(mreTxt0)).when("//*[%s]"%(mreTxt2)).when(closeBtn14).call(self.callBack)
        ctx.when('//*[%s]'%(mreTxt0)).when("//*[%s]"%(mreTxt2)).when(closeBtn11).call(self.callBack)
        ctx.when('//*[%s]'%(mreTxt0)).when('//*[%s]'%(mreTxt2)).when(closeBtn7).call(self.callBack)
        ctx.when('//*[%s]'%(mreTxt0)).when('//*[%s]'%(mreTxt2)).when(closeBtn16).call(self.callBack)
        
        ctx.when('//*[@text="4.8"]').when('//*[%s]'%(mreTxt2)).when(closeBtn8).call(self.callBack)
        ctx.when('//*[@text="4.8"]').when('//*[%s]'%(mreTxt2)).when(closeBtn6).call(self.callBack)
        ctx.when('//*[@text="4.8"]').when('//*[%s]'%(mreTxt2)).when(closeBtn5).call(self.callBack)
        ctx.when('//*[@text="4.8"]').when('//*[%s]'%(mreTxt2)).when(closeBtn10).call(self.callBack)
        ctx.when('//*[@text="4.8"]').when('//*[%s]'%(mreTxt2)).when(closeBtn13).call(self.callBack)
        ctx.when('//*[%s]'%(mreTxt0)).when('//android.widget.RelativeLayout/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.ImageView[4]').when(closeBtn10).call(self.callBack)
        # ctx.when('//*[%s]'%(mreTxt1)).when(closeBtn5).click()
        ctx.when('//*[%s]'%(mreTxt1)).when(closeBtn9).click()
        ctx.when('//*[@text="恭喜获得奖励"]').when("//*[%s]"%(mreTxt2)).when(closeBtn2).click()
        ctx.when('//*[@text="恭喜获得奖励"]').when("//*[%s]"%(mreTxt2)).when(closeBtn1).click()
        ctx.when('//*[@resource-id="root"]/android.view.View[3]/android.view.View[2]/android.view.View[1]/android.view.View[3]').when('//android.widget.ImageView[@index=1]').click()
        ctx.when('//*[@text="今日已签到"]').when('//android.widget.ImageView[@activity="com.qq.e.ads.PortraitADActivity"]').click()
        ctx.when('//*[@text="快手" and @text="4.8"]').when('//android.widget.ImageView[@index=1]').click()
        ctx.when('//*[@text="奖励已领取"]').when('//*[@text="| 跳过"]').click()
        ctx.when('取消安装').click()
        ctx.when('继续安装').when('取消').click()
        # ctx.when('//*[@text="去微信看看"]').when('//android.widget.ImageView').click()
        ctx.when('//*[@text="O1CN01qE4nNy1M45HMjL7jz_!!6000000001380-2-tps-60-60"]').click()
        
        ctx.when('//*[@text="领水滴"]').when('//*[@resource-id="android:id/content"]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.ImageView[1]').click()
        ctx.when('//*[@text="百亿补贴"]').when('//*[@resource-id="android:id/content"]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.ImageView[1]').click()
        ctx.when('//*[@text="去元宝商城使用"]').when('//*[@text="O1CN012FPExu1acnrUXXUgf_!!6000000003351-2-tps-120-120.png_"]').click()

        
        ctx.start()


class Action(Application, WatcherPopup):
    # 初始配置
    def __init__(self):
        super().__init__()
        if (self.sAction != 'test'):
            self.watchStart()

    def reduce3Activity(self, sAction):
        if ('wa' in sAction):
            self.getWalk()
        if ('wo' in sAction):
            self.getWork()
        if ('sh' in sAction):
            self.getShake()
        if ('v' in sAction):
            self.routines()
        if ('b' in sAction):
            self.toBrowse(0)
            self.toBrowse(1)

    # 上滑得步数、元宝、次数
    def toUp(self, num):
        if (self.bStart):
            self.iActionType = num
            self.start()
            self.tapYB3Activity('text', self.iActionType, True)
        
        self.tool.setSleep(8)
        self._d(scrollable=True).scroll(steps=40)
        self.tool.setSleep(1)
        if (num < 2):
            if (self._d(text='浏览商品30秒').exists(timeout=2)):
                self.goRun(400)
        else:
            if (self._d(text='浏览页面30秒').sibling(text='+1次').exists(timeout=2)):
                self.goRun(40)

    # 种田
    def goFarm(self):
        if (self.bStart):
            self.tool.setSleep(3)
            self.el2CE('t', '点淘鸭家园')
            self.tool.setSleep(3)
        self.farm()

    def ot(self):
        # self.start(True).get50tl()
        self.start().topRightRewad()
        for i in range(3):
            self.toUp(i)
        self.start().task()
        self.start().getCashback()
        self.runShortVideo()

    def moveShow3Taps(self):
        self._d(scrollable=True).swipe("up", steps=5)
        self.tool.setSleep(1)
        return self


    def all(self):
        # self.start(True).get50tl()
        self.start().topRightRewad()
        self.start().moveShow3Taps().reduce3Activity('sh-bv')
        self.start().moveShow3Taps().reduce3Activity('wa-bv')
        self.start().moveShow3Taps().reduce3Activity('wo-bv')
        self.start().getCashback()
        self.start().task()
        self.start(True)
        for i in range(3):
            self.toUp(i)
        self.runShortVideo()
        
    # 小视频
    def runShortVideo(self):
        # self._d.watcher.stop()
        if (not self.bStart):
            self.shortVideo()
        else:
            self.start().moveShow3Taps().getShake()
            self.shortVideo()
            self.start().moveShow3Taps().getWork()
            self.shortVideo()
            self.start().moveShow3Taps().getWalk()
            self.shortVideo()



    '''
        wo-[browse | video | auto]
        wo-b|v|a
        wa-b|v|a
        sh-b|v|a
    '''
    def init(self):
        sAction = self.sAction
        if ('-' in sAction):
            self.reduce3Activity(sAction)
        elif (sAction == 'all'):
            print('all')
            self.all()
            self.all()
        elif (sAction == 'aa'):
            print('auto')
            self.all()
            self.all()
        elif (sAction == 'start'):
            self.start()
        elif (sAction == 'gold'):
            self.goWalkGold()
        elif (sAction == 'up'):
            for i in range(3):
                self.toUp(i)
        elif (sAction == 'farm'):
            self.goFarm()
        elif (sAction == 'reward'):
            self.start().topRightRewad()
            self.signIn()
        elif (sAction == 'ot'):
            self.ot()
        elif (sAction == 'task'):
            self.start().task()
        elif ('sv' in sAction):
            if ('sv1' in sAction):
                self.baseWalk()
            elif ('sv2' in sAction):
                self.baseWork()
            elif ('sv3' in sAction):
                self.baseShake()
            self.runShortVideo()
        elif (sAction == 'cb'):
            if (self.bStart): self.start()
            self.getCashback()
        elif (sAction == 'sleep'):
            self.goSleep()
        elif (sAction == 'card'):
            self.cardCollecting()
        else:
            print('test')
            # self.getXml()
            # print(self._d.settings)
            # self.test()
            # self._d(scrollable=True).swipe("up")
            i = 0
            while i < 3:
                self.reuseActions('看直播60秒', '', 70, 1, True)
                i =+ 1





action = Action()
action.init()
print('DONE')


